<?php
/**
 * 商品逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\common\logic;

use app\common\logic\LogicBase;

class Product extends LogicBase
{
    /**
     * 获取商品列表搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 分类筛选
        !empty($data['category']) && $where['s.category'] = $data['category'];
        
        // 状态筛选
        $where['s.status'] = !empty($data['status']) ? $data['status'] : 1;
        
        // 搜索条件：商品名称或品牌
        !empty($data['search_data']) && $where['s.name|s.brand'] = ['like', '%'.$data['search_data'].'%'];
        
        return $where;
    }


    /**
     * 获取首页推荐商品
     */
    public function getHomeRecommend($data = [])
    {
        try {
            $limit = $data['limit'] ?? 10;
            
            // 获取推荐商品（使用数据库实际字段）
            $where = ['status' => 1];
            $field = 'id,name,image_url,market_price';
            $order = 'sort desc,id desc';
            $paginate = ['list_rows' => $limit];
            
            $list = $this->modelProduct->getList($where, $field, $order, $paginate);
            
            // 处理价格变化和字段映射
            foreach ($list as $key => $item) {
                // 字段映射
                $item['current_price'] = $item['market_price'];
                $item['image'] = $item['image_url'];
                
                // 计算价格变化
                $item['change_rate'] = $item['change_rate'] !== null ? round($item['change_rate'], 2) : null;
        $item['change_amount'] = $item['change_amount'] !== null ? round($item['change_amount'], 2) : null;
                $item['price_trend'] = $item['change_rate'] > 0 ? 'up' : ($item['change_rate'] < 0 ? 'down' : 'flat');
                
                // 重新赋值修改后的数据
                $list[$key] = $item;
            }
            
            return $list;
            
        } catch (\Exception $e) {
            return '获取失败：' . $e->getMessage();
        }
    }
    


    /**
     * 获取商品列表
     */
    public function getProductList($where = [], $field = 's.*,pic.path as cover', $order = 's.id desc', $paginate = DB_LIST_ROWS)
    {
        $this->modelProduct->alias('s');

        $this->modelProduct->join = [
            [SYS_DB_PREFIX . 'picture pic', 'pic.id = s.cover_id', 'LEFT']
        ];

        $list = $this->modelProduct->getList($where, $field, $order, $paginate);
        
        // 处理价格变化和字段映射
        foreach ($list as $key => $item)
        {
            // 计算价格变化
            $item['change_rate'] = $item['change_rate'] !== null ? round($item['change_rate'], 2) : null;
            $item['change_amount'] = $item['change_amount'] !== null ? round($item['change_amount'], 2) : null;
            $item['price_trend'] = $item['change_rate'] > 0 ? 'up' : ($item['change_rate'] < 0 ? 'down' : 'flat');
            
            // 重新赋值修改后的数据
            $list[$key] = $item;
        }
        
        return $list;
    }

    /**
     * 获取商品信息
     */
    public function getProductInfo($where = [], $field = true)
    {
        return $this->modelProduct->getInfo($where, $field);
    }
    
    /**
     * 获取商品列表（后台管理专用）
     */
    public function getProductListForAdmin($where = [], $field = true, $order = 'sort desc,id desc', $paginate = DB_LIST_ROWS)
    {
        // 不需要关联查询，直接使用product表的category字段
        
        // 设置查询字段
        if ($field === true) {
            $field = true; // 使用默认字段
        }
        
        // 获取商品列表
        $list = $this->modelProduct->getList($where, $field, $order, $paginate);
        
        // 处理返回数据
        if (!empty($list)) {
            foreach ($list as $key => $item) {
                // 处理图片字段
                $item['cover_image'] = $item['image_url'] ?? '';
                
                // 处理分类文本
                $categoryMap = [
                    'tobacco' => '烟草',
                    'alcohol' => '酒类',
                    'tea' => '茶叶'
                ];
                $item['category_text'] = $categoryMap[$item['category']] ?? '未分类';
                
                // 计算价格变化
                if (isset($item['market_price'])) {
                    $item['change_amount'] = $item['change_amount'] !== null ? round($item['change_amount'], 2) : null;
        $item['change_rate'] = $item['change_rate'] !== null ? round($item['change_rate'], 2) : null;
                    $item['price_trend'] = $item['change_rate'] > 0 ? 'up' : ($item['change_rate'] < 0 ? 'down' : 'flat');
                }
                
                // 处理时间格式
                if (isset($item['create_time']) && is_numeric($item['create_time'])) {
                    $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                }
                
                // 确保库存字段存在
                if (!isset($item['stock'])) {
                    $item['stock'] = 0;
                }
                
                // 重新赋值修改后的数据
                $list[$key] = $item;
            }
        }
            
        return $list;
    }
    
    /**
     * 获取商品详情
     */
    public function getProductDetail($data = [])
    {
        try {
            $product_id = $data['product_id'] ?? $data['id'] ?? 0;
            
            if ($product_id <= 0) {
                return null;
            }
            
            // 尝试从缓存获取商品价格信息
            $cacheData = \app\common\service\PriceCache::getProductPrice($product_id);
            
            // 获取商品详情（后台管理不限制状态）
            $where = ['id' => $product_id];
            $product = $this->modelProduct->getInfo($where);
            
            if (empty($product)) {
                return null;
            }
            
            // 字段映射
            $product['current_price'] = $product['market_price'];
            $product['image'] = $product['image_url'];
            
            // 如果有缓存数据，使用缓存的价格信息
            if ($cacheData !== false) {
                $product['current_price'] = $cacheData['current_price'];
                $product['change_rate'] = $cacheData['change_rate'];
                $product['change_amount'] = $cacheData['change_amount'];
                $product['price_trend'] = $cacheData['price_trend'];
            } else {
                // 计算价格变化
                $product['change_rate'] = $product['change_rate'] !== null ? round($product['change_rate'], 2) : null;
                $product['change_amount'] = $product['change_amount'] !== null ? round($product['change_amount'], 2) : null;
                $product['price_trend'] = $product['change_rate'] > 0 ? 'up' : ($product['change_rate'] < 0 ? 'down' : 'flat');
                
                // 设置缓存
                $priceData = [
                    'current_price' => $product['current_price'],
                    'change_rate' => $product['change_rate'],
                    'change_amount' => $product['change_amount'],
                    'price_trend' => $product['price_trend']
                ];
                \app\common\service\PriceCache::setProductPrice($product_id, $priceData);
            }
            
            // 处理分类信息
            $categoryMap = [
                'tobacco' => '烟草',
                'alcohol' => '酒类', 
                'tea' => '茶叶'
            ];
            $product['category_text'] = $categoryMap[$product['category']] ?? '未分类';
            $product['category_name'] = $product['category_text']; // 兼容性
            
            return $product;
            
        } catch (\Exception $e) {
            return null;
        }
    }
    
    /**
     * 获取商品历史行情
     */
    public function getProductHistory($data = [])
    {
        try {
            $product_id = $data['product_id'] ?? 0;
            $days = $data['days'] ?? 30;
            if ($product_id <= 0) {
                return [RESULT_ERROR, '商品ID不能为空'];
            }
            
            // 尝试从缓存获取历史数据
            $cacheData = \app\common\service\PriceCache::getProductHistory($product_id, $days);
            if ($cacheData !== false) {
                return $cacheData;
            }
            
            $start_time = date('Y-m-d', strtotime("-{$days} days"));
            $end_time = date('Y-m-d');
            
            $where = [
                'product_id' => $product_id,
                'price_date' => ['between', [$start_time, $end_time]]
            ];
            $field = 'price_date,price,change_amount';
            $orderAsc = 'price_date ASC';
            $orderDesc = 'price_date DESC';
            $historyAsc = $this->modelPriceHistory->getList($where, $field, $orderAsc, false);
            $historyMap = [];
            foreach ($historyAsc as $row) {
                $historyMap[$row['price_date']] = [
                    'price' => floatval($row['price']),
                    'change_amount' => $row['change_amount'] !== null ? floatval($row['change_amount']) : null
                ];
            }
            $prevRecord = $this->modelPriceHistory->getInfo([
                'product_id' => $product_id,
                'price_date' => ['<', $start_time]
            ], $field, 'price_date DESC');
            $prevPrice = $prevRecord ? floatval($prevRecord['price']) : null;
            if ($prevPrice === null) {
                $firstInRange = current($historyAsc);
                if ($firstInRange && isset($firstInRange['price'])) {
                    $prevPrice = floatval($firstInRange['price']);
                } else {
                    $prevPrice = floatval($this->modelProduct->getValue(['id' => $product_id], 'market_price'));
                }
            }
            $chart_data = [];
            $list_data = [];
            $cursor = strtotime($start_time);
            $endTs = strtotime($end_time);
            $lastPrice = $prevPrice;
            while ($cursor <= $endTs) {
                $dateStr = date('Y-m-d', $cursor);
                if (isset($historyMap[$dateStr])) {
                    $todayPrice = $historyMap[$dateStr]['price'];
                } else {
                    $todayPrice = $lastPrice;
                }
                $changeAmt = $todayPrice - $lastPrice;
                $chart_data[] = [
                    'date' => $dateStr,
                    'price' => round($todayPrice, 2)
                ];
                $list_data[] = [
                    'date' => $dateStr,
                    'price' => round($todayPrice, 2),
                    'change_amount' => round($changeAmt, 2)
                ];
                $lastPrice = $todayPrice;
                $cursor += 86400;
            }
            $prices = array_column($chart_data, 'price');
            $stats = [
                'max_price' => !empty($prices) ? max($prices) : 0,
                'min_price' => !empty($prices) ? min($prices) : 0,
                'avg_price' => !empty($prices) ? round(array_sum($prices) / count($prices), 2) : 0,
                'total_days' => count($chart_data)
            ];
            usort($list_data, function ($a, $b) { return strcmp($b['date'], $a['date']); });
            $result = [
                'range' => ['start_date' => $start_time, 'end_date' => $end_time, 'days' => $days],
                'chart_data' => $chart_data,
                'date_list' => $list_data,
                'stats' => $stats
            ];
            \app\common\service\PriceCache::setProductHistory($product_id, $days, $result);
            return $result;
            
        } catch (\Exception $e) {
            return '获取失败：' . $e->getMessage();
        }
    }
    
    /**
     * 根据分类获取商品
     */
    public function getProductsByCategory($data = [])
    {
        try {
            $category = $data['category'] ?? '';
            $isVipUser = $data['is_vip_user'] ?? false;
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            // 支持分类ID或分类字符串
            if (is_numeric($category)) {
                $where = ['category_id' => $category, 'product_status' => \app\common\model\Product::PRODUCT_STATUS_ONLINE];
            } else {
                $where = ['category' => $category, 'product_status' => \app\common\model\Product::PRODUCT_STATUS_ONLINE];
            }
            
            // 非VIP用户过滤VIP专享商品
            if (!$isVipUser) {
                $where['is_vip_only'] = 0;
            }
            
            $list = $this->modelProduct->getList($where, true, 'sort desc,id desc', [
                'list_rows' => $limit,
                'page' => $page
            ]);
            
            return $list;
            
        } catch (\Exception $e) {
            return '获取失败：' . $e->getMessage();
        }
    }
    
    /**
     * 根据分类ID获取商品（包含子分类）
     */
    public function getProductsByCategoryId($data = [])
    {
        try {
            $categoryId = $data['category_id'] ?? 0;
            $includeChildren = $data['include_children'] ?? true;
            $isVipUser = $data['is_vip_user'] ?? false;
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            $where = ['product_status' => \app\common\model\Product::PRODUCT_STATUS_ONLINE];
            
            if ($includeChildren) {
                // 获取分类及其所有子分类
                $categoryIds = $this->logicCategory->getCategoryWithChildren($categoryId);
                $where['category_id'] = ['in', $categoryIds];
            } else {
                $where['category_id'] = $categoryId;
            }
            
            // 非VIP用户过滤VIP专享商品
            if (!$isVipUser) {
                $where['is_vip_only'] = 0;
            }
            
            $list = $this->modelProduct->getList($where, true, 'sort desc,id desc', [
                'list_rows' => $limit,
                'page' => $page
            ]);
            
            return $list;
            
        } catch (\Exception $e) {
            return '获取失败：' . $e->getMessage();
        }
    }
    
    /**
     * 搜索商品
     */
    public function searchProducts($data = [])
    {
        try {
            $keyword = $data['keyword'] ?? '';
            $isVipUser = $data['is_vip_user'] ?? false;
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            if (empty($keyword)) {
                return [RESULT_ERROR, '搜索关键词不能为空'];
            }
            
            $where = [
                'product_status' => \app\common\model\Product::PRODUCT_STATUS_ONLINE,
                ['name|brand', 'like', "%{$keyword}%"]
            ];
            
            // 非VIP用户过滤VIP专享商品
            if (!$isVipUser) {
                $where['is_vip_only'] = 0;
            }
            
            $list = $this->modelProduct->getList($where, true, 'sort desc,id desc', [
                'list_rows' => $limit,
                'page' => $page
            ]);
            
            return $list;
            
        } catch (\Exception $e) {
            return '搜索失败：' . $e->getMessage();
        }
    }
    

    /**
     * 获取热门商品
     */
    public function getHotProducts($data = [])
    {
        try {
            $limit = $data['limit'] ?? 10;
            $isVipUser = $data['is_vip_user'] ?? false;
            
            $where = ['product_status' => \app\common\model\Product::PRODUCT_STATUS_ONLINE];
            
            // 非VIP用户过滤VIP专享商品
            if (!$isVipUser) {
                $where['is_vip_only'] = 0;
            }
            
            $list = $this->modelProduct->getList($where, true, 'sales desc,id desc', [
                'list_rows' => $limit
            ]);
            
            return $list;
            
        } catch (\Exception $e) {
            return '获取失败：' . $e->getMessage();
        }
    }
    
    /**
     * 检查商品是否需要VIP权限
     */
    public function checkVipRequired($data = [])
    {
        try {
            $productId = $data['product_id'] ?? 0;
            
            if ($productId <= 0) {
                return [RESULT_ERROR, '商品ID不能为空'];
            }
            
            $product = $this->modelProduct->getInfo(['id' => $productId], 'is_vip_only');
            if (!$product) {
                return [RESULT_ERROR, '商品不存在'];
            }
            
            $isVipRequired = (bool)$product['is_vip_only'];
            
            return ['is_vip_required' => $isVipRequired];
            
        } catch (\Exception $e) {
            return '检查失败：' . $e->getMessage();
        }
    }
    


    /**
     * 商品状态切换
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function productStatus($data = [])
    {
        $where = ['id' => $data['id']];
        $update = ['product_status' => $data['status'], 'update_time' => time()];
        
        $url = url('product/productlist');

        $result = $this->modelProduct->updateInfo($where, $update);
        
        $result && action_log('状态', '商品状态切换，id：' . $data['id'] . '，product_status：' . $data['status']);
        
        return $result ? [RESULT_SUCCESS, '状态切换成功', $url] : [RESULT_ERROR, $this->modelProduct->getError()];
    }

    /**
     * 商品删除
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function productDel($data = [])
    {
        try {
            $productId = $data['id'] ?? 0;
            
            if ($productId <= 0) {
                return [RESULT_ERROR, '商品ID不能为空'];
            }
            
            // 检查商品是否存在
            $product = $this->modelProduct->getInfo(['id' => $productId]);
            if (!$product) {
                return [RESULT_ERROR, '商品不存在'];
            }
            
            // 软删除商品（设置status为删除状态）
            $result = $this->modelProduct->updateInfo(['id' => $productId], [
                'status' => DATA_DELETE,
                'update_time' => time()
            ]);

            $url = url('product/productlist');
            
            if ($result) {
                // 记录操作日志
                action_log('删除', '商品删除，id：' . $productId . '，商品名称：' . $product['name']);
                
                return [RESULT_SUCCESS, '商品删除成功', $url];
            } else {
                return [RESULT_ERROR, '商品删除失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '删除失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 编辑商品
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function productEdit($data = [])
    {
        try {
            $productId = $data['id'] ?? 0;
            
            if ($productId <= 0) {
                return [RESULT_ERROR, '商品ID不能为空'];
            }
            
            // 检查商品是否存在
            $product = $this->modelProduct->getInfo(['id' => $productId]);
            if (!$product) {
                return [RESULT_ERROR, '商品不存在'];
            }
            
            // 更新商品信息
            $result = $this->modelProduct->setInfo($data);
            
            if ($result) {
                return [RESULT_SUCCESS, '商品编辑成功'];
            } else {
                return [RESULT_ERROR, '商品编辑失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '编辑失败：' . $e->getMessage()];
        }
    }

    /**
     * 添加浏览历史
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function addViewHistory($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $productId = $data['product_id'] ?? 0;
            
            if ($userId <= 0) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            if ($productId <= 0) {
                return [RESULT_ERROR, '商品ID不能为空'];
            }
            
            // 检查商品是否存在
            $product = $this->modelProduct->getInfo(['id' => $productId], 'id,name');
            if (!$product) {
                return [RESULT_ERROR, '商品不存在'];
            }
            
            // 创建浏览历史模型实例
             $viewHistoryModel = new \app\common\model\ProductViewHistory();
             
             // 检查是否已存在浏览记录，如果存在则更新时间
             $existHistory = $viewHistoryModel->getInfo([
                 'user_id' => $userId,
                 'product_id' => $productId
             ]);
             
             if ($existHistory) {
                 // 更新浏览时间
                 $result = $viewHistoryModel->updateInfo([
                     'user_id' => $userId,
                     'product_id' => $productId
                 ], [
                     'view_time' => time(),
                     'update_time' => time()
                 ]);
             } else {
                 // 新增浏览记录
                 $result = $viewHistoryModel->updateInfo([], [
                     'user_id' => $userId,
                     'product_id' => $productId,
                     'view_time' => time(),
                     'create_time' => time(),
                     'update_time' => time()
                 ]);
             }
            
            if ($result) {
                return [RESULT_SUCCESS, '浏览历史记录成功'];
            } else {
                return [RESULT_ERROR, '浏览历史记录失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '记录失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户浏览历史
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getUserViewHistory($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            if ($userId <= 0) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            // 创建浏览历史模型实例
            $viewHistoryModel = new \app\common\model\ProductViewHistory();
            
            // 设置关联查询
            $viewHistoryModel->join = [
                ['product p', 'p.id = pvh.product_id', 'LEFT']
            ];
            
            $where = ['pvh.user_id' => $userId];
            $field = 'pvh.*, p.name, p.image_url, p.market_price, p.yesterday_price, p.category';
            $order = 'pvh.view_time desc';
            $paginate = ['list_rows' => $limit, 'page' => $page];
            
            $list = $viewHistoryModel->alias('pvh')->getList($where, $field, $order, $paginate);
            
            // 处理数据格式
            foreach ($list as $key => $item) {
                // 字段映射
                $item['current_price'] = $item['market_price'];
                $item['image'] = $item['image_url'];
                
                // 计算价格变化
                $change_amount = $item['market_price'] - $item['yesterday_price'];
                $change_rate = $item['yesterday_price'] > 0 ? ($change_amount / $item['yesterday_price']) * 100 : 0;
                
                $item['change_rate'] = $change_rate !== null ? round($change_rate, 2) : null;
        $item['change_amount'] = $change_amount !== null ? round($change_amount, 2) : null;
                $item['price_trend'] = $change_rate > 0 ? 'up' : ($change_rate < 0 ? 'down' : 'flat');
                
                // 格式化浏览时间
                $item['view_time_formatted'] = date('Y-m-d H:i', $item['view_time']);
                
                // 重新赋值修改后的数据
                $list[$key] = $item;
            }
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }

    /**
     * 商品详情页综合数据
     * 包含：商品基本信息、价格历史、关注状态、相关推荐、统计数据
     * @author 王勇程 <laughskydragon@qq.com>
     * 暂时关闭，因为这是api专用方法
     */
    public function getDetailPage($data = [])
    {
        return false;//暂时关闭，因为这是api专用方法
        
        try {
            $productId = $data['product_id'] ?? 0;
            $userId = $data['user_id'] ?? 0;
            
            if ($productId <= 0) {
                return [RESULT_ERROR, '商品ID不能为空'];
            }
            
            // 获取商品基本信息
            $product = $this->modelProduct->getInfo(['id' => $productId, 'status' => 1]);
            if (!$product) {
                return [RESULT_ERROR, '商品不存在或已下架'];
            }
            
            // 字段映射
            $product['current_price'] = $product['market_price'];
            $product['image'] = $product['image_url'];
            
            // 计算价格变化（详情页不强制需要，存在才处理）
            if (isset($product['change_rate'])) {
                $product['change_rate'] = $product['change_rate'] !== null ? round($product['change_rate'], 2) : null;
            }
            if (isset($product['change_amount'])) {
                $product['change_amount'] = $product['change_amount'] !== null ? round($product['change_amount'], 2) : null;
            }
            if (isset($product['change_rate'])) {
                $product['price_trend'] = $product['change_rate'] > 0 ? 'up' : ($product['change_rate'] < 0 ? 'down' : 'flat');
            }

            // 多图
            $product['images'] = $this->modelPicture->getList([
                'id' => ['in', explode(',', $product['img_ids'])],
                'status' => 1
            ], 'path', 'id', false);
            
            // 获取价格历史（最近30天）
            $priceHistory = $this->getProductHistory(['product_id' => $productId]);
            
            // 获取相关推荐商品
            // $relatedProducts = $this->getProductList(['category_id' => $product['category_id']]);
            
            // 如果用户已登录，检查关注状态
            $isFollowed = false;
            if ($userId > 0) {
                $followInfo = $this->modelUserFollow->getInfo([
                    'user_id' => $userId,
                    'product_id' => $productId
                ]);
                $isFollowed = !empty($followInfo);
            }
            
            $result = [
                'product' => $product,
                'price_history' => $priceHistory,
                // 'related_products' => $relatedProducts,
                'is_followed' => $isFollowed,
                // 'statistics' => [
                //     'view_count' => 0, // 暂时设为0，后续可扩展
                //     'follow_count' => 0 // 暂时设为0，后续可扩展
                // ]
            ];
            
            return [RESULT_SUCCESS, '获取成功', $result];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }

    /**
     * 商品列表页综合数据
     * 包含：商品列表、分类信息、筛选条件、热门推荐
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getListPage($data = [])
    {
        try {
            // 获取商品列表
            $productList = $this->getProductList($data);
            
            // 获取分类信息
            $categoryLogic = new \app\common\logic\Category();
            $categories = $categoryLogic->getCategoryList(['parent_id' => 0, 'status' => 1]);
            
            // 获取热门推荐
            $hotProducts = $this->getHotProducts(['limit' => 6]);
            
            // 筛选条件
            $filters = [
                'sort_options' => [
                    ['text' => '综合排序', 'value' => 'default'],
                    ['text' => '价格从低到高', 'value' => 'price_asc'],
                    ['text' => '价格从高到低', 'value' => 'price_desc'],
                    ['text' => '最新发布', 'value' => 'time_desc']
                ]
            ];
            
            $result = [
                'product_list' => $productList,
                'categories' => $categories,
                'hot_products' => $hotProducts,
                'filters' => $filters
            ];
            
            return [RESULT_SUCCESS, '获取成功', $result];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }

    /**
     * 商品搜索页综合数据
     * 包含：搜索结果、热门搜索、搜索建议、相关分类
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getSearchPage($data = [])
    {
        try {
            $keyword = $data['keyword'] ?? '';
            
            if (empty($keyword)) {
                return [RESULT_ERROR, '搜索关键词不能为空'];
            }
            
            // 获取搜索结果
            $searchResults = $this->searchProduct($data);
            
            // 热门搜索关键词（暂时使用固定数据）
            $hotSearches = [
                '苹果', '香蕉', '橙子', '牛肉', '猪肉', '鸡蛋'
            ];
            
            // 搜索建议（基于关键词的相关建议）
            $suggestions = [];
            if (strlen($keyword) > 0) {
                // 这里可以实现更复杂的搜索建议逻辑
                $suggestions = [$keyword . '价格', $keyword . '行情', $keyword . '批发'];
            }
            
            // 相关分类
            $categoryLogic = new \app\common\logic\Category();
            $relatedCategories = $categoryLogic->getCategoryList(['status' => 1, 'limit' => 10]);
            
            $result = [
                'search_results' => $searchResults,
                'hot_searches' => $hotSearches,
                'suggestions' => $suggestions,
                'related_categories' => $relatedCategories,
                'keyword' => $keyword
            ];
            
            return [RESULT_SUCCESS, '获取成功', $result];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
}